package com.game.core.dbcs.executor;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.core.dbcs.DBCSConst;
import com.game.core.dbcs.config.DbConfigInfo;
import com.game.core.dbcs.config.PackageItemInfo;
import com.game.core.dbcs.config.SqlMapXmlReader;
import com.game.core.dbcs.daoproxy.IDaoExecutor;
import com.game.core.dbcs.dbspace.DBSpace;

/**
 * DAO接口函数执行代理管理器
 * @author
 */
public class ExecutorManager
{
	private static Map<String, ExecutorProxy> executorMap = new ConcurrentHashMap<String, ExecutorProxy>();
	private static Logger logger = LoggerFactory.getLogger(ExecutorManager.class);

	public static void initialize(DbConfigInfo... dbConfigInfo)
	{
		String tmpBeanName;
		String tmpPkgName;

		for(DbConfigInfo config: dbConfigInfo){
			Collection<PackageItemInfo> tmpPkgItemInfos = DBSpace.getDBZone(config.getSqlMapXMLPath()).getMapperItems();
			if (tmpPkgItemInfos != null)
			{
				for (PackageItemInfo tmpPkgInfo : tmpPkgItemInfos)
				{
					tmpBeanName = tmpPkgInfo.BeanName;
					tmpBeanName = tmpBeanName.substring(0, tmpBeanName.length() - SqlMapXmlReader.SUFFIX.length());
					tmpPkgName = tmpPkgInfo.PackageName.replace('/', '.');
	
					regMapperExecutor(tmpBeanName, tmpPkgName, config.getSqlMapXMLPath(),false);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static void regMapperExecutor(String beanname, String namespace, String sqlMapXMLPath,boolean isGameDataZone)
	{
		String tmpExecutorClassName = namespace + "." + DBCSConst.EXECUTOR_INTERFACE_PREFIX + beanname + DBCSConst.EXECUTOR_INTERFACE_SUFFIX;
		if (executorMap.containsKey(tmpExecutorClassName))
			return;

		Class<? extends IDaoExecutor> tmpExecutorClass = null;
		try
		{
			tmpExecutorClass = (Class<? extends IDaoExecutor>) Class.forName(tmpExecutorClassName);
		}
		catch (ClassNotFoundException e)
		{
//			e.printStackTrace();
			logger.error("invaild className={},",tmpExecutorClassName,e);
		}
		if (tmpExecutorClass == null)
		{
			// XXX: 待处理，暂时返回NULL
			return;
		}

		if (!tmpExecutorClass.isInterface())
		{
			return;
		}

		ExecutorProxy tmpMapperProxy = new ExecutorProxy(beanname,sqlMapXMLPath);
		tmpMapperProxy.initialize(tmpExecutorClass);
		executorMap.put(tmpMapperProxy.getExcutorInterfaceName(), tmpMapperProxy);
	}

	@SuppressWarnings("unchecked")
	public static <T extends IDaoExecutor> T getExector(Class<T> interfaceClass)
	{
		ExecutorProxy tmpMapperProxy = executorMap.get(interfaceClass.getSimpleName());
		return (tmpMapperProxy != null && tmpMapperProxy.isAvailable()) ? (T) tmpMapperProxy.getExecutor() : null;
	}

}
